<template>
    <div class="mod-prod">
        <avue-crud
            ref="crud"
            :data="dataList"
            :option="tableOption"
            :page="page"
            :permission="permission"
            :table-loading="dataListLoading"
            @search-change="searchChange"
            @selection-change="selectionChange"
            @refresh-change="refreshChange"
            @on-load="getDataList"
            @row-del="deleteHandle"
        >
            <template slot="menuLeft">
                <!-- 如需新增按钮可取消注释 -->
                <!--
                <el-button
                    icon="el-icon-plus"
                    size="small"
                    type="primary"
                    @click.stop="addOrUpdateHandle()">
                    新增
                </el-button>
                <el-button
                    v-if="isAuth('shop:pickAddr:delete')"
                    :disabled="dataListSelections.length <= 0"
                    size="small"
                    type="danger"
                    @click="deleteHandle()">
                    批量删除
                </el-button>
                -->
            </template>

            <template slot-scope="scope" slot="careStatus">
                <el-tag v-if="scope.row.careStatus === '0'" size="small" type="danger">未关怀</el-tag>
                <el-tag v-else size="small">已关怀</el-tag>
            </template>

            <template slot="menu" slot-scope="scope">
                <!--
                <el-button
                    icon="el-icon-edit"
                    size="small"
                    type="primary"
                    @click="addOrUpdateHandle(scope.row.id)">
                    修改
                </el-button>
                -->
                <el-button
                    icon="el-icon-delete"
                    size="small"
                    type="danger"
                    @click="deleteHandle(scope.row.id)">
                    删除
                </el-button>
            </template>
        </avue-crud>

        <add-or-update
            v-if="addOrUpdateVisible"
            ref="addOrUpdate"
            @refreshDataList="refreshChange">
        </add-or-update>
    </div>
</template>

<script>
import { tableOption } from '@/crud/customer/personTaskLogList'
import AddOrUpdate from '@/views/modules/customer/custcarerule-add-update.vue'

export default {
    components: { AddOrUpdate },
    data() {
        return {
            dataForm: {
                prodName: ''
            },
            permission: {
                delBtn: this.isAuth('prod:prod:delete')
            },
            dataList: [],
            page: {
                total: 0,           // 总记录数（非总页数！）
                currentPage: 1,     // 当前页
                pageSize: 10,       // 默认每页10条
                pageSizes: [10, 20, 50, 100] // 可选每页数量
            },
            addOrUpdateVisible: false,
            dataListSelections: [],
            dataListLoading: false,
            tableOption: tableOption,
            resourcesUrl: process.env.VUE_APP_RESOURCES_URL
        }
    },
    mounted() {
        this.initSelectData()
    },
    methods: {
        initSelectData() {
            this.$http({
                url: this.$http.adornUrl('/crm/base/emp/page'),
                method: 'get',
                params: this.$http.adornParams({
                    current: 1,
                    size: 999
                })
            }).then(({ data }) => {
                const targetColumn = this.tableOption.column.find(col => col.prop === "custManName");
                if (targetColumn) {
                    this.$set(targetColumn, 'dicData', data.obj.records || []);
                }
            });
        },

        // 获取数据列表
        getDataList(page, params, done) {
            this.dataListLoading = true;

            // 合并分页参数
            const currentPage = page?.currentPage || this.page.currentPage;
            const pageSize = page?.pageSize || this.page.pageSize;

            let searchParams = {};
            if (params && params.custManName) {
                searchParams.custManId = params.custManName;
            }

            this.$http({
                url: this.$http.adornUrl('/crm/base/cusRule/getCareTaskList'),
                method: 'get',
                params: this.$http.adornParams({
                    current: currentPage,
                    size: pageSize,
                    ...searchParams
                })
            }).then(({ data }) => {
                // 假设后端返回格式为：{ obj: { records: [...], total: 123 } }
                const result = data.obj || {};
                this.dataList = result.records || [];
                this.page.total = result.total || 0; // 关键：设置总记录数，分页器才正常

                this.dataListLoading = false;
                if (done) done();
            }).catch(() => {
                this.dataList = [];
                this.page.total = 0;
                this.dataListLoading = false;
                if (done) done();
            });
        },

        addOrUpdateHandle(id) {
            this.addOrUpdateVisible = true;
            this.$nextTick(() => {
                this.$refs.addOrUpdate.init(id);
            });
        },

        deleteHandle(id) {
            const ids = id ? [id] : this.dataListSelections.map(item => item.id);
            if (!ids || ids.length === 0) {
                this.$message.warning('请至少选择一条记录');
                return;
            }

            this.$confirm(`确定删除选中的 ${ids.length} 条记录?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$http({
                    url: this.$http.adornUrl(`/crm/base/cusRule/${ids.join(',')}`),
                    method: 'delete',
                    data: this.$http.adornData({ id: ids }, false)
                }).then(({ data }) => {
                    this.$message.success('删除成功');
                    this.refreshChange(); // 刷新当前页
                });
            }).catch(() => {});
        },

        searchChange(params, done) {
            this.page.currentPage = 1; // 搜索时重置到第一页
            this.getDataList(this.page, params, done);
        },

        selectionChange(val) {
            this.dataListSelections = val;
        },

        getSeleProdIds() {
            return this.dataListSelections.map(item => item.prodId);
        },

        refreshChange() {
            this.getDataList(this.page);
        }
    }
}
</script>
